<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon style="position: relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div style="position: absolute; top: 4px; right: 10px">
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #toolbar>
        <Dropdown placement="bottom">
          <Button type="primary" class="mr-2">添加仪表盘</Button>
          <template #overlay>
            <Menu @click="addRuleClick">
              <MenuItem key="newRule">
                <Icon icon="material-symbols:file-copy-sharp" /> 创建新的仪表盘</MenuItem
              >
            </Menu>
          </template>
        </Dropdown>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:edit-filled',
                tooltip: {
                  title: '编辑',
                  placement: 'top',
                },
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:eye-filled',
                tooltip: {
                  title: '详情',
                  placement: 'top',
                },
                onClick: handleMore.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                tooltip: {
                  title: '删除',
                  placement: 'top',
                },
                disabled: record.root,
                onClick: handleDelete.bind(null, record),
              },
            ]"
            :drop-down-actions="[
              //仪表盘未开发完成。。。。。。。。。
              // {
              //   icon: 'ant-design:setting-filled',
              //   label: '配置仪表盘',
              //   onClick: handleAllocation.bind(null, record),
              // },
              {
                icon: 'material-symbols:download-2',
                label: '导出仪表盘',
                onClick: handleDownload.bind(null, record),
              },
              {
                icon: 'ic:sharp-share',
                label: '仪表盘设为公开',
                disabled: record.public,
                onClick: handleOpen.bind(null, record),
              },
              {
                icon: 'octicon:reply',
                label: '私有',
                disabled: !record.public,
                onClick: handlePrivate.bind(null, record),
              },
              {
                icon: 'material-symbols:person-pin',
                label: '管理已分配的客户',
                onClick: AssignToCustomers.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <PublicDrawer
      @register="registerDrawer"
      @update-desc-data="handleUpdateDescData"
      :show-tabs="['detail', 'auditLogs', 'version']"
    />
    <AddDashboards @register="registerModal" @close-add-rule-falg="closeAddRuleFalg" />
    <ShareToCustomers @register="shareRegisterModal" @close-share-flag="closeAddRuleFalg" />
  </div>
</template>
<script lang="ts" setup>
  import { ICON } from '/@/enums/iconEnum';
  import { Alert, Tooltip } from 'ant-design-vue';
  import PublicDrawer from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.vue';
  import { ENTITY_TYPE } from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.data';
  import { Dropdown, Button, Menu, MenuItem } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import Icon from '/@/components/Icon';

  import { dashboardParams } from '/@/api/thingsborad/dashboards/model/dashboardModel';
  import {
    getDashboard,
    deleteDashboard,
    publicDashboard,
    privateDashboard,
    downloadDashboard,
    getTheDashboardInfo,
  } from '/@/api/thingsborad/dashboards/dashboard';
  import { onMounted, ref } from 'vue';
  import AddDashboards from './AddDashboards.vue';
  import { useModal } from '/@/components/Modal';
  import dayjs from 'dayjs';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useDrawer } from '/@/components/Drawer';
  import { useRoute } from 'vue-router';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import { dashboardColumns, searchFormSchema, detailSchema } from './dashboards.data';
  // import { useGo } from '/@/hooks/web/usePage';
  import ShareToCustomers from './ShareToCustomers.vue';
  // const go = useGo();
  const { createConfirm } = useMessage();
  const checkedKeys = ref<any>([]);

  let params = ref<dashboardParams>({
    pageSize: 10,
    page: 0,
    sortProperty: 'createdTime',
    sortOrder: 'DESC',
    type: 'CORE',
  });
  let tableData = ref<Array<any>>([]);
  const route = useRoute();
  onMounted(() => {
    // 初始化表格数据
    if (route.params.id === undefined) {
      setProps({
        api: getDashboard,
        beforeFetch: (val) => {
          params.value.page = val.page - 1;
          params.value.pageSize = val.pageSize;
          params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
          params.value.sortProperty = 'createdTime';

          if (val.deptName === null) {
            params.value.textSearch = undefined;
          } else {
            params.value.textSearch = val.deptName;
          }
          return params.value;
        },
        afterFetch: (res) => {
          tableData.value = [];
          if (res.length === 0) {
            return tableData.value;
          }

          res.forEach((item) => {
            tableData.value.push({
              createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
              title: item.title,
              public:
                item.assignedCustomers === null || item.assignedCustomers.length === 0
                  ? false
                  : item.assignedCustomers[0].public,
              assignedCustomers:
                item.assignedCustomers === null || item.assignedCustomers.length === 0
                  ? '--'
                  : item.assignedCustomers[0].title,
              id: item.id.id,
              info: item,
            });
          });

          return tableData.value;
        },
        fetchSetting: {
          pageField: 'page',
          sizeField: 'pageSize',
          listField: 'data',
          totalField: 'totalElements',
        },
      });
    } else {
      setProps({
        api: getDashboard,
        beforeFetch: (val) => {
          params.value.page = val.page - 1;
          params.value.pageSize = val.pageSize;
          params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
          params.value.sortProperty = 'createdTime';

          if (val.deptName === null) {
            params.value.textSearch = undefined;
          } else {
            params.value.textSearch = val.deptName;
          }
          let data: any = {
            id: route.params.id,
            params: params.value,
          };
          return data;
        },
        afterFetch: (res) => {
          tableData.value = [];
          if (res.length === 0) {
            return tableData.value;
          }
          res.forEach((item) => {
            tableData.value.push({
              createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
              title: item.title,
              public:
                item.assignedCustomers === null || item.assignedCustomers.length === 0
                  ? false
                  : item.assignedCustomers[0].public,
              assignedCustomers:
                item.assignedCustomers === null || item.assignedCustomers.length === 0
                  ? '--'
                  : item.assignedCustomers[0].title,
              id: item.id.id,
              info: item,
            });
          });

          return tableData.value;
        },
        fetchSetting: {
          pageField: 'page',
          sizeField: 'pageSize',
          listField: 'data',
          totalField: 'totalElements',
        },
      });
    }
  });
  const [registerDrawer, { openDrawer }] = useDrawer();

  const [registerModal, { openModal, setModalProps }] = useModal();
  const [shareRegisterModal, { openModal: shareOpenModal, setModalProps: shareSetModalProps }] =
    useModal();
  //表格初始化
  const [registerTable, { reload, setProps }] = useTable({
    title: '仪表盘',
    columns: dashboardColumns,
    ...tableStyleSetting,
    formConfig: {
      layout: 'horizontal',
      schemas: searchFormSchema,
      showAdvancedButton: false,
      submitFunc: async () => {
        reload();
      },
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 8 },
        lg: { span: 6, offset: 12 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });
  // 多选删除
  const handleSelectedDelete = () => {
    createConfirm({
      iconType: 'info',
      title: `确定要删除  '${checkedKeys.value.length}' 个仪表板吗？`,
      content: '请注意：确认后，所有选定的仪表板将被删除，所有相关数据将不可恢复。',
      onOk: async () => {
        for (const item of checkedKeys.value) {
          await deleteDashboard(item);
        }
        reload();
        //初始化 表格数据
        checkedKeys.value = [];
      },
    });
  };

  // 多选
  function onSelect(record, selected) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected, _selectedRows, changeRows) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  // 抽屉详情数据更改
  const handleUpdateDescData = (value) => {
    value.assetName = value.name;
    value.assetConfiguration = value.assetProfileName;
    value.label = value.label;
    value.customer = value.customerTitle;
    value.isOpen = value.customerIsPublic;
  };
  function handleMore(record: Recordable) {
    openDrawer(true, {
      entityType: ENTITY_TYPE.DASHBOARD,
      entityId: record.id,
      title: record.title,
      api: getTheDashboardInfo,
      detailSchema: detailSchema,
      params: record.id,
    });
  }

  function handleEdit(record: Recordable) {
    setModalProps({
      title: '编辑仪表盘',
      okText: '保存',
    });

    openModal(true, record);
  }
  function AssignToCustomers(record: Recordable) {
    shareSetModalProps({
      title: '管理已分配的客户',
      okText: '保存',
    });
    shareOpenModal(true, record);
  }
  function handlePrivate(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要将仪表盘盘 ${record.title} 设为个私有吗？`,
      content: '确认后，仪表板将被设为私有，不能被其他人访问。。',
      onOk: async () => {
        await privateDashboard(record.id);
        reload();
        //初始化 表格数据
        checkedKeys.value = [];
      },
    });
    //
  }
  async function handleOpen(record: Recordable) {
    try {
      await publicDashboard(record.id);

      createConfirm({
        iconType: 'info',
        title: '仪表盘' + record.title + '已被公开',
        content:
          `<div>http://${import.meta.env.VITE_IP_PORT}/dashboard/e21c0070-e7ef-11ee-818f-41a6f6398a5e?publicId=4af392d0-9e16-11ee-99f6-535103f50c3f</div><div>提示： 不要忘记将相关设备公开以访问其数据。</div>`,
        onOk: async () => {
          reload();
          //初始化 表格数据
          checkedKeys.value = [];
        },
      });
    } catch (error) {}
  }
  async function handleDownload(record: Recordable) {
    try {
      const theResourceFileData = await downloadDashboard(record.id);

      const blob = new Blob([JSON.stringify(theResourceFileData)], { type: 'text/plain' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = record.title + '.json'; // 设置下载后的文件名
      document.body.appendChild(link); // 需要添加到DOM中才能触发点击事件
      link.click();
      document.body.removeChild(link); // 下载后移除元素
      window.URL.revokeObjectURL(url); // 释放内存
    } catch (error) {}
  }
  //配置仪表盘
  // function handleAllocation(record: Recordable) {
  //   go({
  //     path: '/tb-dashboards/ConfigureDashboard',
  //     query: {
  //       id: record.id,
  //     },
  //   });
  // }

  async function handleDelete(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要删除仪表板   '${record.title}'  吗？`,
      content: '请注意：确认后，仪表板及其所有相关数据将不可恢复。',
      onOk: async () => {
        await deleteDashboard(record.id);
        reload();
      },
    });
  }
  // 添加规则链点击事件
  function addRuleClick(value) {
    if (value.key === 'newRule') {
      setModalProps({
        title: '添加仪表盘',
        okText: '保存',
      });
      openModal(true, true);
    }
  }
  // 组件通信 addrule 弹窗关闭
  function closeAddRuleFalg() {
    // 初始化表格数据
    reload();
  }
</script>
